/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Principal;

import Comunicacion.PuertoSerial;
import com.rapplogic.xbee.api.*;
import com.rapplogic.xbee.api.zigbee.NodeDiscover;
import com.rapplogic.xbee.api.zigbee.ZNetRxResponse;
import com.rapplogic.xbee.api.zigbee.ZNetTxRequest;
import java.awt.Color;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.print.DocFlavor;
import javax.swing.JComboBox;

/**
 *
 * @author ALDAJO
 */
public class SquidMonitor extends javax.swing.JFrame implements PacketListener{

    /**
     * Creates new form SquidMonitor
     */
    //creamos las variables del programa
    private XBee xbee = null;
    private int [] messages;
    private HashMap<String, XBeeAddress64> addrsXbeeSquids;     //to remove
    
    public SquidMonitor(){
        initComponents();
        this.setResizable(false);
        xbee = new XBee();                                      //to remove
        String bcName = "Broadcast";
        addrsXbeeSquids = new HashMap<>();                      //to remove
        addrsXbeeSquids.put(bcName, XBeeAddress64.BROADCAST);   //to remove
        jTextArea1.setBackground(Color.BLACK);
        jTextArea1.setForeground(Color.white);
        jTextArea1.setEditable(false);
        addr64TextList.setBackground(Color.BLACK);
        addr64TextList.setForeground(Color.white);
        addr64TextList.setEditable(false);
        //to remove
        addr64TextList.setText("Identificacion\tDireccion 64 Bits\nBroadcast\t" + XBeeAddress64.BROADCAST);
        jLabel1.setText("Seleccione un dispositivo");
        jComboBox1.removeAllItems();
        jComboBox1.setEnabled(false);
        jComboBox1.addItem(bcName);
        ButtonOnOff.setEnabled(false);        
        try {
            xbee.open(PuertoSerial.identifierPortName(), 9600);//to remove
            jTextArea1.setText("Bienvenido...\n");
        } catch (XBeeException ex) {
            Logger.getLogger(SquidMonitor.class.getName()).log(Level.SEVERE, null, ex);
        }
        xbee.addPacketListener(this);                          //to remove
        //System.out.println("ZNET_RX_RESPONSE: " + Integer.toHexString(ApiId.ZNET_RX_RESPONSE.getValue()));
    }
    
    //método para registrar los datos en el jtextArea
    private void setDatajTextArea(String text){
        jTextArea1.setText(jTextArea1.getText() + text + "\n");
    }
    
    private void setDataAddr64TextList(String string1, XBeeAddress64 x64){
        addr64TextList.setText(addr64TextList.getText() + "\n" + string1 + "\t" + x64.toString());
    }
    
    //método para enviar el paquete de datos
    //to remove
    private void sendMA(XBeeAddress64 addr64, int[] data) {
        //int[] stringToInts = stringToInts(s);
        ZNetTxRequest request = new ZNetTxRequest(addr64, data);
        try {
            //envía el mensaje
            //ZNetTxStatusResponse response = (ZNetTxStatusResponse)
            xbee.sendAsynchronous(request);
        } catch (XBeeTimeoutException ex) {
            Logger.getLogger(SquidMonitor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (XBeeException ex) {
            Logger.getLogger(SquidMonitor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    //RETO: Método para organizar los datos del hastable para imprimir o una clase
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        connectButton = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jComboBox1 = new javax.swing.JComboBox();
        ClearButton = new javax.swing.JButton();
        ButtonOnOff = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        addr64TextList = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextArea1.setColumns(20);
        jTextArea1.setEditable(false);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        connectButton.setText("To Conect");
        connectButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectButtonActionPerformed(evt);
            }
        });

        jButton1.setText("Search Devices");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jComboBox1.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jComboBox1ItemStateChanged(evt);
            }
        });

        ClearButton.setText("Clear");
        ClearButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ClearButtonActionPerformed(evt);
            }
        });

        ButtonOnOff.setText("On");
        ButtonOnOff.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                ButtonOnOffMousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                ButtonOnOffMouseReleased(evt);
            }
        });
        ButtonOnOff.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ButtonOnOffActionPerformed(evt);
            }
        });

        jLabel1.setText("jLabel1");

        jLabel2.setText("jLabel2");

        addr64TextList.setColumns(20);
        addr64TextList.setRows(5);
        jScrollPane2.setViewportView(addr64TextList);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ButtonOnOff, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(30, 30, 30)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 320, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(ClearButton, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(65, 65, 65)
                        .addComponent(connectButton, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 449, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(ButtonOnOff)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 328, Short.MAX_VALUE)))
                    .addComponent(jScrollPane1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ClearButton, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(connectButton, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectButtonActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_connectButtonActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        setDatajTextArea("Buscando Dispositivos...");
        try {
            //xbee.sendAsynchronous(new AtCommand("NT"));
            xbee.sendAsynchronous(new AtCommand("ND"));
        } catch (XBeeException ex) {
            Logger.getLogger(SquidMonitor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void ClearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ClearButtonActionPerformed
        // TODO add your handling code here:
        jTextArea1.setText("");
    }//GEN-LAST:event_ClearButtonActionPerformed

    private void ButtonOnOffMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ButtonOnOffMousePressed
        // TODO add your handling code here:
        messages = new int[1];
        messages[0] = 0x0b;
        String tempName = (String)jComboBox1.getSelectedItem();
        XBeeAddress64 tempAddr64 = addrsXbeeSquids.get(tempName);
        sendMA(tempAddr64, messages);
        setDatajTextArea(tempName + ": Encendiendo <ON>");
        messages = null;
        tempAddr64 = null;
        tempName = null;
    }//GEN-LAST:event_ButtonOnOffMousePressed

    private void ButtonOnOffActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonOnOffActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_ButtonOnOffActionPerformed

    private void ButtonOnOffMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ButtonOnOffMouseReleased
        // TODO add your handling code here:
        messages = new int[1];
        messages[0] = 0x1b;
        String tempName = (String)jComboBox1.getSelectedItem();
        XBeeAddress64 tempAddr64 = addrsXbeeSquids.get(tempName);
        sendMA(tempAddr64, messages);
        setDatajTextArea(tempName + ": Encendiendo <OFF>");
    }//GEN-LAST:event_ButtonOnOffMouseReleased

    private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBox1ItemStateChanged
        // TODO add your handling code here:
    }//GEN-LAST:event_jComboBox1ItemStateChanged

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SquidMonitor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SquidMonitor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SquidMonitor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SquidMonitor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new SquidMonitor().setVisible(true);
                
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton ButtonOnOff;
    private javax.swing.JButton ClearButton;
    private javax.swing.JTextArea addr64TextList;
    private javax.swing.JButton connectButton;
    private javax.swing.JButton jButton1;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration//GEN-END:variables

    @Override
    public void processResponse(XBeeResponse xbr) {
        //throw new UnsupportedOperationException("Not supported yet.");
        System.out.println("Mensaje Recibido=" + xbr);
        //Node Discover
        if (xbr.getApiId() == ApiId.AT_RESPONSE) {
            NodeDiscover nd = NodeDiscover.parse((AtCommandResponse)xbr);
            System.out.println("at response");
            XBeeAddress64 tempAddr = nd.getNodeAddress64();
            String nodeName = nd.getNodeIdentifier();
            if(!addrsXbeeSquids.containsValue(tempAddr)){
                addrsXbeeSquids.put(nodeName, tempAddr);
                jComboBox1.addItem(nodeName);
                jComboBox1.setEnabled(true);
                ButtonOnOff.setEnabled(true);
                setDatajTextArea("Dispositivo localizado");
                setDatajTextArea("Dirección: " + tempAddr + " Identificacion: " + nodeName);
                setDataAddr64TextList(nodeName, tempAddr);
                System.out.println("Node discover response is: " + nd);
            }
            tempAddr = null;
            nodeName = null;
        } else if (xbr.getApiId() == ApiId.TX_STATUS_RESPONSE) {
            return;
        } else if (xbr.getApiId() == ApiId.ZNET_RX_RESPONSE) {
            setDatajTextArea("llegó un dato...");
            ZNetRxResponse r = (ZNetRxResponse) xbr;
            System.out.print(r.getData());
            //el siguiete reto es hacer que con solo llegar los datos se pueda obtener
            //la direccion y la identificacion del dispositivo
            //PISTA: se debe enviar el comando remoto AT "NI" 
            if(!addrsXbeeSquids.containsValue(r.getRemoteAddress64())){
                
            }
        } else {
            //System.out.println("ERROR: mensaje desconocido =" + response.getApiId());
        }
    }
}